package com.easytouch.core;

import android.os.SystemClock;

import com.easytouch.core.utils.Log;


/**
 * Created by gulin on 2017/11/27.
 */

public class ChargeThread {

    public static final int MAX_LINE = 4;

    private Log mlogger; //日志

    private long[] mLineTime;

    private volatile boolean isStopped = true;

    //private ChargingThread mThread = null;

    private static class Holder{
        private static ChargeThread INSTANCE = new ChargeThread();
    }

    private ChargeThread()
    {
        mlogger = new Log("ChargeThread.txt");
        mLineTime = new long[MAX_LINE];
        //mThread = new ChargingThread();
        isStopped = true;
    }

    public static ChargeThread getInstance()
    {
        return ChargeThread.Holder.INSTANCE;
    }

    public boolean requestCharge(final int line)
    {
        if(line < 1 || line > mLineTime.length)
        {
            return false;
        }
        if(mLineTime[line - 1] != 0)
        {
            return false;
        }
        if(!DriverThread.getInstance().setChargeState(line, true))
        {
            return false;
        }
        mLineTime[line - 1] = System.currentTimeMillis();
        if(isStopped)
        {
            //mThread.start();
            new Thread(new ChargingThread()).start();
        }
        mlogger.i("charge start line " + String.valueOf(line));
        return true;
    }

    private class ChargingThread implements Runnable {

        @Override
        public void run() {
            isStopped = false;
            while (true) {
                SystemClock.sleep(1000);
                long systemTime = System.currentTimeMillis();
                boolean isAllZero = true;
                for (int i = 0; i < mLineTime.length; i++) {
                    long time = mLineTime[i];
                    if (time == 0) {
                        continue;
                    }
                    isAllZero = false;
                    if (systemTime - time >= 1000 * 60 * 61) //已经达到一小时了(多加1分钟)
                    {
                        mLineTime[i] = 0;
                        DriverThread.getInstance().setChargeState(i + 1, false);
                        mlogger.i("charge end line " + String.valueOf(i + 1));
                    }
                }
                if (isAllZero) {
                    break;
                }
            }
            isStopped = true;
        }
    }
}
